<!-- src/components/LoginForm.vue -->
<template>
  <div class="login">
    <h2>Login</h2>
    <!--    @submit:监听-->
    <!--    .prevent：这是 Vue 事件修饰符，表示阻止事件的默认行为。在表单的情况下，默认行为是提交表单并刷新页面。.prevent 修饰符会调用 event.preventDefault() 来阻止这个默认行为。-->
    <form @submit.prevent="login">
      <div>
        <label for="username">Username:</label>
        <input type="text" id="username" v-model="username" required/>
      </div>
      <div>
        <label for="password">Password:</label>
        <input type="password" id="password" v-model="password" required/>
      </div>
      <button type="submit">Login</button>
    </form>
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script>
import {login} from "@/api/user";

export default {
  name: "LoginForm",
  data() {
    return {
      username: '',
      password: '',
      error: '',
    };
  },
  methods: {
    async login() {
      try {
        console.log(this.username, this.password);
        const response = await login({
              username: this.username,
              pwd: this.password
            }
        )
        const response_data = response.data
        if (response_data.code === 'fail') {
          this.error = response_data.msg;
        } else {
          localStorage.setItem('token', response_data.data.token);
          this.$router.push('/user-list');
        }
      } catch (error) {
        console.log(error);
        if (error.response && error.response.data) {
          this.error = error.response.data;
        } else {
          this.error = 'Network error';
        }
      }
    }
  }
}

</script>


<style scoped>
.login {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: linear-gradient(to right, #6a11cb, #2575fc);
  color: white;
}

form {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

form div {
  margin-bottom: 15px;
}

form label {
  margin-right: 10px;
}

form input {
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  background: #2575fc;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background: #6a11cb;
}
</style>
